--
-- Author: shunguo.chen
-- Date: 2016-11-18 17:54:01
--
-- MallPanel 商城

local ScrollViewExtend = require("app.widget.ScrollViewExtend")
local TabsBtn = require("app.widget.TabsBtn")
local MallRender = import(".renders.MallRender")
local ResRender = require("app.widget.renders.ResRender")
local IconRender = require("app.widget.renders.IconRender")
local AuctionKeyboardPanel = require("app.auction.views.AuctionKeyboardPanel")

local ClassRef = app.mvc.createPanelClass(...)

local MONEY_TIP_STR = L("demondShop_notenough")
local NUM_TIP_STR = L("demondShop_buytimes_notenough")
local BUY_NUM_STR = L("demondShop_buy_num")
local BUY_TOTAL_PRICE_STR = L("demondShop_buy_totalprice")
local RUSH_STR = L("demondShop_service_nushtobuy")
local TIME_LIMIT_STR = L("demondShop_obtainedtime")

function ClassRef.create(node)
	local sprite = ClassRef.extend(node)
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	-- dumpNodeChildren(self, "MallPanel")

	-- tlt --
	self._coinRender = ResRender.create(self._ui.Panel_money)
    self._coinRender:setData({type = Enums.TipsType.daibi, id = 98, num = 0})

    if app:isInnerEma() or app:isInnerPwrd() then
    	self._crystalRender = ResRender.create(self._ui.Panel_crystal)
    	self._crystalRender:setVisible(true)
    	self._crystalRender:isNeedSetIcon(true)
        self._crystalRender:setData({type = Enums.TipsType.daibi, id = 115, num = 0})
    end

    -- left panel --
	self._sv = ScrollViewExtend.create(self._ui.ScrollView, {class = MallRender})

	local leftPanel = self._ui.Panel_img
	local btns = {0,0,0,0,0,0}
	local nameTexts = {0,0,0,0,0,0}
	local newImgs = {0,0,0,0,0,0}
    local innerPublisher = app:getInnerPublisher()
	for i=1,6 do
		btns[i] = leftPanel:getChildByName("Button_" .. i)
		nameTexts[i] = leftPanel:getChildByName("name_" .. i)
		newImgs[i] = leftPanel:getChildByName("dotNew_" .. i)

        if i == 5 then
            nameTexts[i]:setString(L("shopname_73051_" .. innerPublisher))
        elseif i == 6 then
            nameTexts[i]:setString(L("shopname_73061_" .. innerPublisher))
        end
	end
    local function onTabsBtn(index)
    	if self._curIdx then
    		nameTexts[self._curIdx]:setOpacity(127)
    		self._curIdx = index
    		executeFunc(self._onOperate, "switchMallShop", self._curIdx)
	    else
	    	self._curIdx = index
	    end

	    nameTexts[index]:setOpacity(255)
    end
    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, 1)
    self._newImgs = newImgs

    -- right panel -
    -- detail
    local detailPanel = self._ui.Panel_top
    self._nameText = detailPanel:getChildByName("name")
    self._iconRender = IconRender.create(detailPanel:getChildByName("icon"))
    self._iconRender:setTipEnable(true)
    self._iconRender:setTipUnShowOrigin(true)
    self._typeText = detailPanel:getChildByName("tips_1")
    self._bindText = detailPanel:getChildByName("tips_2")
    self._descText = detailPanel:getChildByName("text")

    -- limit
    self._tltPanel = detailPanel:getChildByName("Panel_tlt")
    self._singleTlt = detailPanel:findChild("Panel_tlt/text_1")
    self._singleLimitText = self._singleTlt:getChildByName("text_4")
    self._doubleTlt = detailPanel:findChild("Panel_tlt/text")
    self._rushLimitText = self._doubleTlt:getChildByName("text_3")
    self._timeLimitText = self._doubleTlt:getChildByName("text_2")

    -- buy
    local buyPanel = self._ui.Panel_buy

    self._lookBtn = buyPanel:getChildByName("btn_look")
    self._lookBtn:addClickEventListener(function()
    	executeFunc(self._onOperate, "preview", self._avatarData)
    end)

    self._buyBtn = buyPanel:getChildByName("btn_buy")
    self._buyBtn:addClickEventListener(function()
    	if self._buyTipStr then
    		if self._buyTipStr == MONEY_TIP_STR then
    			executeFunc(self._onOperate, "needPay", MONEY_TIP_STR)
    		else
		    	display.pushToast(self._buyTipStr)
		    end
	    else
	    	local params = {goodsId=self._data.id, num=self._curNum}
	    	executeFunc(self._onOperate, "buyItem", params)
	    end
    end)

    -- self._unitPriceText = buyPanel:findChild("Panel_num/num_1")
    self._unitRealPriceText = buyPanel:findChild("Panel_num/num_2")
    self._unitRealPriceIcon = buyPanel:findChild("Panel_num/gold")

    local numPanel = buyPanel:getChildByName("Panel_supplies")
    self._numPanel = numPanel
    display.uiAddClick(numPanel, function()
        self:_showKeyboard()
    end)
    self._addBtn = numPanel:getChildByName("Button_plus")
    self._subBtn = numPanel:getChildByName("Button_minus")
    self._addBtn:addClickEventListener(function()
    	 self._curNum = self._curNum + 1
    	 self:_refreshNumPanel()
    end)
    self._subBtn:addClickEventListener(function()
    	 self._curNum = self._curNum - 1
    	 self:_refreshNumPanel()
    end)

    self._buyNumText = numPanel:getChildByName("num_1")
    numPanel:getChildByName("num_2"):setTouchEnabled(false)
    self._totalPriceText = numPanel:findChild("num_2/num")
    self._totalPriceIcon = numPanel:findChild("num_2/gold")
    self._totalPriceColor = self._totalPriceText:getColor()
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

function ClassRef:updateCoin(num)
	self._coinRender:setNum(num)
end

function ClassRef:updateCrystal(num)
    if self._crystalRender then
        self._crystalRender:setNum(num)
    end
end

function ClassRef:getAllRenders()
	return self._sv:getVisibleRenders()
end

function ClassRef:setShopIndex(selectIndex)
    self._tabsBtn:initSelectStatus()
    self._tabsBtn:pressBtn(selectIndex, true)
end

function ClassRef:getDatas()
    return self._datas
end

function ClassRef:_onClickRender(render)
	self._isNeedRefresh = false

	if self._curRender then
		self._curRender:setSelected(false)
	end
	self._curRender = render
	render:setSelected(true)
	self:setData(render:getData())
end

-- datas = {MallVo, ...}
-- renderIdx = 选中的render，默认第一个
function ClassRef:refreshShop(datas, renderIdx, flag)
	-- print("refreshShop", renderIdx, #datas)
    self._datas = datas
	renderIdx = renderIdx or 1
    local hasData = #datas > 0
    self._sv:setVisible(hasData)
    self._ui.Panel_top:setVisible(hasData)
    self._ui.Panel_buy:setVisible(hasData)
    self._ui.Panel_tips:setVisible(not hasData)
    if hasData then
    	self._isNeedRefresh = true
    	self._sv:showDataList(datas, 0, handler(self, self._onClickRender), function()
    		if self._isNeedRefresh then
    			self._isNeedRefresh = false
    			self:_onClickRender(self._sv:getVisibleRender(renderIdx))
    		end
    	end)
    	if renderIdx <= #datas then
    		self:setData(datas[renderIdx])
		end
		if flag then -- 来源跳转选中某个物品后顶格显示
			local off = self._sv:getInnerContainerSize().height - self._sv:getContentSize().height
			if off > 0 then
				local renderPosY = self._sv:_getRenderPos(renderIdx).y
				local renderHeight = self._sv.renderHei
				local off2 = math.max(0, off - (self._sv:getInnerContainerSize().height - math.abs(renderPosY + renderHeight)))
        		self._sv:jumpToPercentVertical(math.max(0, math.min(100, 100 * (1-off2/off))))
			end
		end
    end
end

-- 商店页签暂时不要红点
function ClassRef:refreshBtnsNew(news)
	-- for i,img in ipairs(self._newImgs) do
	-- 	img:setVisible(news[i])
	-- end
end

function ClassRef:setData(data)
	if self._data == data then
		self._curNum = self._curNum or 1
	else
		self._curNum = 1
	end
	self.super.setData(self, data)
end

-- data = MallVo
function ClassRef:refresh()
    self:_hideKeyboard()

	local itemData = self._data:getShowItemData()
	self._nameText:setString(self._data:getName())
	self._iconRender:setData(itemData)
	self._typeText:setString(itemData:getTypeName())
	self._bindText:setString(itemData.getBindStr and itemData:getBindStr() or "")
	self._descText:setString(self._data:getDesc())

	-- limit
	self:_refreshLimit()

	-- avatar preview
	local avatarEnable, avatarData = itemData:isClassAvatarEnable()
	display.setBtnTouchEnable(self._lookBtn, avatarEnable)
	self._avatarData = avatarData

	-- unit price
	local unitPanel = self._unitRealPriceText:getParent()
	local unitDot = unitPanel:getChildByName("dot")
	local unitGoldIcon = unitPanel:getChildByName("gold")
	local unitTlt = unitPanel:getChildByName("tlt")
	self._unitRealPriceText:setString(self._data.price)
	display.setNodesMiddle(unitPanel, unitDot, unitTlt, unitGoldIcon, self._unitRealPriceText)

	-- num panel
    self._unitRealPriceIcon:loadTexture(self._data:getDaibiSmallIcon())
    self._totalPriceIcon:loadTexture(self._data:getDaibiSmallIcon())
    self._curNum = 1
	self:_refreshNumPanel()
end

function ClassRef:_refreshLimit()
	local data = self._data
	local strAry = {}

	local isRushBuy = data:isRushBuy()
	if isRushBuy then
		strAry[#strAry + 1] = string.format(RUSH_STR, data.svrLimitNowCount, data.svrLimitMaxCount)
	end
	
	local isTimeLimit = data:isTimeLimit()
	if isTimeLimit then
		local isOpen, gap = data:checkOpen()
		if isOpen and gap > 0 then
			local timeStr = TimeUtil.secondsToTime(gap)
			strAry[#strAry + 1] = string.format(TIME_LIMIT_STR, timeStr)
		end
	end

	local len = #strAry
	self._tltPanel:setVisible(len ~= 0)
	if len > 0 then
		self._singleTlt:setVisible(len == 1)
		self._doubleTlt:setVisible(len == 2)
		if len == 2 then
			self._rushLimitText:setString(strAry[1])
			self._timeLimitText:setString(strAry[2])
		else
			self._singleLimitText:setString(strAry[1])
		end
	end

	-- 可以rushBuy通过拉取服务器信息每秒更新，只有在单独限时需要每秒刷新
	if isTimeLimit then
		self:performWithDelay(function()
			self:_refreshLimit()
		end, 1)
	end
end

function ClassRef:_refreshNumPanel()
	self._buyTipStr = nil

	local numMax = self._data:getBuyNumMax()
	local realNumMax = numMax
	local price = self._data.price
    local daibiId = self._data:getDaibiId()
	if numMax > 0 then
		local daibi = UD:getDaibiValue(daibiId)
		realNumMax = math.min(numMax, math.floor(daibi/price))
	else
		self._buyTipStr = NUM_TIP_STR
	end
	if numMax == 0 then
        self._curNum = 0
        self._numMin = 0
        self._numMax = 0
        self._realNumMax = 0
    else
        self._numMin = 1
        self._numMax = numMax
        self._realNumMax = realNumMax
    end

	display.setBtnTouchEnable(self._subBtn, self._curNum > 1)
	display.setBtnTouchEnable(self._addBtn, self._curNum < realNumMax)
    self._numPanel:setTouchEnabled(self._numMin < realNumMax)
	self._buyNumText:setString(string.format(BUY_NUM_STR, self._curNum, numMax))

	if self._curNum > realNumMax then
		self._totalPriceText:setColor(display.COLOR_RED_NOTICE)

        -- 暂时只有魔晶和钻石两种，如果新加需要额外处理
        if daibiId == Enums.lootType.coin then
            self._buyTipStr = MONEY_TIP_STR
        else
    		self._buyTipStr = string.format(L("auction_tips9"), self._data:getDaibiName())
        end
	else
		self._totalPriceText:setColor(self._totalPriceColor)
	end

	local numPrice = self._curNum * price
	if numPrice == 0 then numPrice = price end
	self._totalPriceText:setString(string.format(BUY_TOTAL_PRICE_STR, numPrice))
	local totalPanel = self._totalPriceText:getParent()
	local totalPriceGoldIcon = totalPanel:getChildByName("gold")
	display.setNodesMiddle(totalPanel, nil, self._totalPriceText, totalPriceGoldIcon)
end

function ClassRef:_showKeyboard()
    if not self._keyboard then
        local node = self._ui.Panel_buy:getChildByName("Node_keyboard")
        local keyboard = AuctionKeyboardPanel.create(node)
        keyboard:setShowNumText(false)
        keyboard:setNumLimit(0, 999)
        keyboard:onOperate(function(op, num)
            if op == "numChange" then
                self._buyNumText:setString(num)
            elseif op == "closeMiniKeyboard" then
                num = math.max(num, self._numMin)
                num = math.min(num, self._realNumMax)
                if num == self._curNum then
                    -- 数量未变 恢复之前的string
                    self._buyNumText:setString(string.format(BUY_NUM_STR, self._curNum, self._numMax))
                else
                    self._curNum = num
                    self:_refreshNumPanel()
                end
                self:_hideKeyboard()
            end
        end)

        -- 点击空白区域关闭
        display.nodeRemoveForNotHit(keyboard:getPanel(), function()
            self:_hideKeyboard()
            self._buyNumText:setString(string.format(BUY_NUM_STR, self._curNum, self._numMax))
        end)

        self._keyboard = keyboard
    end

    self._keyboard:show()
    self._keyboard:setNum(0)
    self._buyNumText:setString(self._curNum)
end

function ClassRef:_hideKeyboard()
    if self._keyboard then
        self._keyboard:hide()
    else
        self._ui.Panel_buy:getChildByName("Node_keyboard"):setVisible(false)
    end
end

return ClassRef